package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired// 根据类型注入
    private UserMapper userMapper;

    @Override
    public void update(User user) {

        user.setUpdateTime(LocalDateTime.now()); // 设置更新时间
        userMapper.update(user);// 调用userMapper的update方法,传入user对象
    }

    // 根据用户名查询用户
    @Override
    public User findByUsername(String username) {
        User u= userMapper.findByUsername(username);// 根据用户名查询用户,用u来接收查询结果
        return u;
    }

    // 注册用户
    @Override
    public void register(String username, String password) {
        // 加密密码
        String md5String= Md5Util.getMD5String(password);// 调用Md5Util工具类的getMD5String方法,将密码加密

        userMapper.addUser(username, md5String);// 调用userMapper的addUser方法,将用户名和加密后的密码传入

    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();// 从ThreadLocal中获取用户信息

        Integer id = (Integer) map.get("id");// 从map中获取用户id

        userMapper.updateAvatar(avatarUrl,id);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();// 从ThreadLocal中获取用户信息

        Integer id = (Integer) map.get("id");// 从map中获取用户id

        userMapper.updatePwd(Md5Util.getMD5String(newPwd),id);// 调用userMapper的updatePwd方法,传入加密后的新密码和用户id
    }
}
